package net

import (
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/dreadl0ck/tlsx"
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
	"log"
	"packet_capture/bean"
	"strconv"
	"time"
)

// GetDevice /** 获取网络设备
func GetDevice() (devs []pcap.Interface) {
	// 得到所有的(网络)设备
	devices, err := pcap.FindAllDevs()
	if err != nil {
		log.Fatal(err)
	}
	return devices
}

// GetDeviceData /** 获取网卡数据
func GetDeviceData(device string, data func(packet gopacket.Packet)) {
	handle, err := pcap.OpenLive(device, 5120, false, 30*time.Second)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()
	// Use the handle as a packet source to process all packets
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		data(packet)
	}
}

// PrintTls /** 打印TLS层数据
func PrintTls(packet gopacket.Packet) {
	clientHello := tlsx.GetClientHello(packet)
	if clientHello != nil {
		marshal, _ := json.Marshal(clientHello)
		fmt.Printf("PrintTls： %s\n", string(marshal))
	}
}

// PrintHex /** 打印16进制数据分析
func PrintHex(data []byte) {
	fmt.Printf("%s\n", hex.Dump(data))
}

// GetDestData /** 获取目标数据
func GetDestData(packet gopacket.Packet) *bean.TcpMeta {
	tcpLayer := packet.Layer(layers.LayerTypeTCP)
	if tcpLayer != nil {
		tcp, _ := tcpLayer.(*layers.TCP)
		ipv4Layer := packet.Layer(layers.LayerTypeIPv4)
		if ipv4Layer != nil {
			ipv4, _ := ipv4Layer.(*layers.IPv4)
			port := int(tcp.DstPort)
			return &bean.TcpMeta{
				Port: port,
				Ip:   ipv4.DstIP.String(),
			}
		}
	}
	return nil
}

// GetSrcData /** 获取源数据
func GetSrcData(packet gopacket.Packet) *bean.TcpMeta {
	tcpLayer := packet.Layer(layers.LayerTypeTCP)
	if tcpLayer != nil {
		tcp, _ := tcpLayer.(*layers.TCP)
		ipv4Layer := packet.Layer(layers.LayerTypeIPv4)
		if ipv4Layer != nil {
			ipv4, _ := ipv4Layer.(*layers.IPv4)
			port, _ := strconv.Atoi(tcp.SrcPort.String())
			return &bean.TcpMeta{
				Port: port,
				Ip:   ipv4.SrcIP.String(),
			}
		}
	}
	return nil
}
